package exp1;

import practice.BagInterface;

import java.util.Arrays;

/**
 * Created by 蜡笔小新丶 on 2017/9/22.
 */
public class MyArrayList<T> implements BagInterface<T> {
    Object bags1[], bags2[];

    public <T> MyArrayList() {
        bags1 = new Object[10];
    }

    public boolean isEmptey() {
        boolean result = false;
        int num = 0;
        for (int i = 0; i < bags1.length; i++)
            if (bags1[i] == null)
                num++;
        if (num == bags1.length)
            result = true;
        return result;
    }

    private boolean isfull(T arr[]) {
        boolean result = false;
        int num = arr.length;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == null)
                num = arr.length - 1;
        }
        if (num == arr.length)
            result = true;
        return result;
    }

    private int emptey(T arr[]) {
        int i = 0;
        while (true) {
            if (arr[i] == null)
                break;
            i++;
        }
        return i;
    }

    private Object[] become(T[] arr) {
        bags2 = new Object[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            bags2[i] = arr[i];
        }
        return bags2;
    }

    @Override
    public boolean add(T thing) {
        if (isfull((T[]) bags1)) {
            bags1 = (T[]) become((T[]) bags1);
            bags1[emptey((T[]) bags1)] = thing;
        } else
            bags1[emptey((T[]) bags1)] = thing;
        return true;
    }

    public boolean remove(T thing) {
        boolean result = false;
        int A = 0;
        int i = 0;
        while (bags1[i] != null && i<bags1.length){
                if (bags1[i].equals(thing)) {
                    A = i;
                    result = true;
                    break;
                }else
                    i++;
        }
        while (A != bags1.length-1) {
            bags1[A] = bags1[A + 1];
            A++;
        }
        bags1[A] = null;
        return result;
    }

    @Override
    public String toString() {
        return "bags1=" + Arrays.toString(bags1);
    }
}